package com.hongyi.modelcontest.modular.contest.service;

import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hongyi.modelcontest.core.common.page.LayuiPageFactory;
import com.hongyi.modelcontest.core.shiro.ShiroKit;
import com.hongyi.modelcontest.core.shiro.ShiroUser;
import com.hongyi.modelcontest.core.util.AuthCode;
import com.hongyi.modelcontest.core.util.DateUtils;
import com.hongyi.modelcontest.core.util.IdUtil;
import com.hongyi.modelcontest.modular.contest.entity.ContestInfo;
import com.hongyi.modelcontest.modular.contest.entity.ContestRegistRecord;
import com.hongyi.modelcontest.modular.contest.entity.CustomerInfo;
import com.hongyi.modelcontest.modular.contest.mapper.ContestInfoMapper;
import com.hongyi.modelcontest.modular.contest.mapper.ContestRegistRecordMapper;
import com.hongyi.modelcontest.modular.contest.mapper.CustomerInfoMapper;
import com.hongyi.modelcontest.modular.contest.vo.ContestRegister;
import com.hongyi.modelcontest.modular.contest.vo.DeptVo;
import com.hongyi.modelcontest.modular.contest.vo.RecordVo;
import com.hongyi.modelcontest.modular.system.entity.Dept;
import com.hongyi.modelcontest.modular.system.entity.User;
import com.hongyi.modelcontest.modular.system.mapper.UserMapper;
import com.hongyi.modelcontest.modular.system.service.DeptService;
import com.hongyi.modelcontest.modular.wechat.utils.ExcelUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Service
public class RecordService {
    @Resource
    private ContestRegistRecordMapper contestRegistRecordMapper;
    @Resource
    private CustomerInfoMapper customerInfoMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private ContestInfoMapper contestInfoMapper;
    @Resource
    private AuthCode authCode;
    @Resource
    private DeptService deptService;

    public IPage list(String conditions) {
        Page<RecordVo> page = LayuiPageFactory.defaultPage();
        List<RecordVo> recordVos = getRecordVos(conditions, page);
        page.setRecords(recordVos);
        return page;
    }

    private List<RecordVo> getRecordVos(String conditions, Page<RecordVo> page) {
        List<RecordVo> recordVos;//总部管理员
        ShiroUser user = ShiroKit.getUser();
        if (user.getRoleList().contains(1099513167015673858L)) {
            if (page != null) {
                recordVos = contestRegistRecordMapper.selectRecordPage(page, conditions, null, null);
            } else {
                recordVos = contestRegistRecordMapper.selectRecordPage(conditions, null, null);
            }
        } else if (user.getRoleList().contains(1099506373501480962L)) {
            //先查询所有的下级 deptId

            List<Long> deptIdList = getChildDeptList(user.getDeptId());
            deptIdList.add(user.getDeptId());
            String s = StringUtils.collectionToDelimitedString(deptIdList, ",");
            if (page != null) {
                recordVos = contestRegistRecordMapper.selectRecordPage(page, conditions, null, s);
            } else {
                recordVos = contestRegistRecordMapper.selectRecordPage(conditions, null, s);

            }
            //代理商管理员
        } else {
            if (page != null) {
                recordVos = contestRegistRecordMapper.selectRecordPage(page, conditions, user.getId(), null);
            } else {
                recordVos = contestRegistRecordMapper.selectRecordPage(conditions, user.getId(), null);
            }
        }
        return recordVos;
    }

    private List<Long> getChildDeptList(Long deptId) {
        List<Long> ids = new ArrayList<>();
        List<Dept> childList = deptService.list(new QueryWrapper<Dept>().lambda()
                .eq(Dept::getPid, deptId));
        if (!CollectionUtils.isEmpty(childList)) {
            for (Dept dept : childList) {
                ids.add(dept.getDeptId());
                List<Long> childDeptList = getChildDeptList(dept.getDeptId());
                ids.addAll(childDeptList);
            }
        }
        return ids;
    }

    @Transactional
    public String register(ContestRegister register) {
        ContestInfo contestInfo = contestInfoMapper.selectOne(new QueryWrapper<ContestInfo>().lambda()
                .orderByDesc(ContestInfo::getCreatedTime).last(" limit 1"));
        if (contestInfo.getRegistEndTime().getTime() < System.currentTimeMillis()) {
            throw new ServiceException(500, "活动已结束！");
        }
        CustomerInfo info = customerInfoMapper.selectOne(new QueryWrapper<CustomerInfo>().lambda()
                .eq(CustomerInfo::getWechatOpenid, register.getOpenId()));
        if (info == null) {
            info = new CustomerInfo();

            info.setCustomerId(IdUtil.getId() + "");
            info.setWechatOpenid(register.getOpenId());
            customerInfoMapper.insert(info);
        }
        ContestRegistRecord record = contestRegistRecordMapper.selectOne(new QueryWrapper<ContestRegistRecord>().lambda()
                .eq(ContestRegistRecord::getCustomerId, info.getCustomerId())
                .eq(ContestRegistRecord::getContestId, register.getContestId()));
        ContestRegistRecord contest = new ContestRegistRecord();
        if (record != null) {
            contest.setId(record.getId());
        }
        contest.setCustomerId(info.getCustomerId());
        contest.setContestId(contestInfo.getContestId());
        contest.setChildName(register.getChildName());
        contest.setChildGender(register.getChildGender());
        contest.setChildBirthdate(register.getChildBirthdate());
        contest.setPhotoUrl(register.getPhotoUrl());
        contest.setParentName(register.getParentName());
        contest.setParentPhone(register.getParentPhone());
        contest.setAgentId(register.getAgentId());
        contest.setDeptId(register.getDeptId() + "");
        contest.setIntroducer(register.getIntroducer());
        if (contest.getId() != null) {
            contestRegistRecordMapper.updateById(contest);
        } else {
            contestRegistRecordMapper.insert(contest);
        }
        return info.getCustomerId();
    }

    public List<RecordVo> detail(String openId, String contestId) {
        return contestRegistRecordMapper.selectDetail(openId, contestId);
    }

    public Long saveDept(DeptVo deptVo) {
        if (!deptVo.getCode().equals(authCode.getCode(deptVo.getPhone()))) {
            throw new ServiceException(500, "验证码错误");
        }
        authCode.deleteCode(deptVo.getPhone());
        User account = userMapper.selectOne(new QueryWrapper<User>().lambda()
                .eq(User::getAccount, deptVo.getPhone()));
        if (account != null) {
            if (!deptVo.getOpenId().equals(account.getOpenId())) {
                account.setUpdateUser(0L);
                account.setOpenId(deptVo.getOpenId());
                userMapper.updateById(account);
            }
            return account.getUserId();
        } else {
            throw new ServiceException(500, "账户不存在，请联系管理员！");
        }
    }

    public Map<String, Object> listVo() {
        List<ContestRegistRecord> list = contestRegistRecordMapper.selectList(new QueryWrapper<ContestRegistRecord>().lambda()
                .orderByDesc(ContestRegistRecord::getCreatedTime));
        Map<String, Object> result = new HashMap<>(2);
        List<Map<String, String>> resultlist = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (ContestRegistRecord record : list) {
                Map<String, String> map = new HashMap<>(2);
                map.put("name", record.getChildName());
                map.put("photo", record.getPhotoUrl());
                resultlist.add(map);
            }
            result.put("totalNum", resultlist.size());
            result.put("records", resultlist);
            return result;
        }
        result.put("totalNum", 0);
        result.put("records", Collections.EMPTY_LIST);
        return result;
    }

    public void excel(String conditions, HttpServletResponse response) {
        List<RecordVo> records = this.getRecordVos(conditions, null);
        if (!CollectionUtils.isEmpty(records)) {
            String[] titles = {
                    "赛事号",
                    "赛事名称",
                    "儿童姓名",
                    "性别",
                    "出生日期",
                    "家长姓名",
                    "联系电话",
                    "代理商",
                    "代理人",
                    "报名时间"
            };
            List<String[]> dataList = new ArrayList<>();
            for (RecordVo vo : records) {
                String[] datas = {
                        vo.getContestId(),
                        vo.getContestName(),
                        vo.getChildName(),
                        "M".equals(vo.getChildGender()) ? "男" : "女",
                        DateUtils.toString(vo.getChildBirthdate()),
                        vo.getParentName(),
                        vo.getParentPhone(),
                        vo.getSimpleName(),
                        vo.getAgentName(),
                        DateUtils.toString(vo.getCreatedTime())
                };
                dataList.add(datas);
            }
            ExcelUtils.writeList("报名列表.xls", dataList, titles, response);
        }
    }
}
